<template>
  <el-drawer
    size="60%"
    v-model="dialogVisibled"
    :before-close="handleClose"
    :title="dialogTitle"
    :close-on-click-modal="false"
    @open="handleDialogOpen"
  >
    <template #header>
      <span style="font-weight: 600; color: black">{{ dialogTitle }}</span>
    </template>
    <el-divider />
    <div class="divStyle">
      <el-form
        ref="ruleFormRef"
        :model="model"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="规则名称" prop="RuleName">
          <el-input
            v-model="model.RuleName"
            placeholder="规则名称"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      
        <el-form-item label="匹配规则" prop="AnalysisRule_CN">
          <el-input
            v-model="model.AnalysisRule_CN"
            readonly
            placeholder="匹配规则"
          >
            <template #append
              ><el-button
                style="background-color: #409eff; color: white"
                type="primary"
                @click="setDataRuleClick"
                >设置规则</el-button
              ></template
            >
          </el-input>
        </el-form-item>
      
        <el-form-item label="是否启用" prop="IsOpen">
          <el-switch
            v-model="model.IsOpen"
            class="ml-2"
            width="60"
            inline-prompt
            active-text="启用"
            inactive-text="不启用"
          />
        </el-form-item>
        <el-form-item label="规则备注" prop="Remark">
          <el-input
            v-model="model.Remark"
            :rows="2"
            type="textarea"
            placeholder="规则备注"
            maxlength="200"
          />
        </el-form-item>
      </el-form>
    </div>

    <!--嵌套抽屉-->
    <el-drawer
      size="50%"
      v-model="innerDrawer"
      title="设置匹配规则"
      :append-to-body="true"
      :before-close="closeInnerDrawerClick"
    >
      <template #header>
        <span style="font-weight: 600; color: black">设置匹配规则</span>
      </template>
      <el-divider />
      <div class="divStyle">
        <matchFormula
          :data="pageList"
          :matchFieldData="matchFieldDataList"
          :matchEquation="matchEquationList"
          :menuId="menuId"
          :corporationKey="corporationKey"
          :systemKey="systemKey"
          ref="childRef"
        ></matchFormula>
        <el-input
          v-model="previewDataRule"
          :rows="2"
          type="textarea"
          placeholder="预览公式"
        />
      </div>
      <template #footer>
        <div style="position: relative; top: 10px">
          <el-button
            icon="Close"
            size="large"
            type="danger"
            plain
            @click="closeInnerDrawerClick"
            >取消</el-button
          >
          <el-button
            type="primary"
            size="large"
            icon="Check"
            plain
            @click="previewClick"
            >预览</el-button
          >
          <el-button
            type="success"
            size="large"
            icon="Check"
            plain
            @click="confirmDataRuleClick"
            >确认规则</el-button
          >
        </div>
      </template>
    </el-drawer>

    <template #footer>
      <div style="position: relative; top: 10px">
        <el-button
          icon="Close"
          size="large"
          type="danger"
          plain
          @click="handleClose"
          >取消</el-button
        >
        <el-button
          type="success"
          size="large"
          icon="Check"
          plain
          @click="saveClick(ruleFormRef)"
          >保存</el-button
        >
      </div>
    </template>
  </el-drawer>
</template>
      <script  lang="ts">
import {
  onMounted,
  defineComponent,
  PropType,
  computed,
  ref,
  reactive,
} from "vue";
import { SysDataRule, SysDataRuleInput } from "@/model/dataRule";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import matchFormula from "@/components/matchFormula.vue";
import {
  matchingData,
  matchingSelectExtendOutPut,
  matchResultData,
  randamId,
  showControlDataSourceEnum,
  showDataControlEnum,
} from "@/model/match";
import { ButtonRoleTypeEnum, RuleTypeEnum } from "@/enum/public";
import {
  GetDataRuleConfig,
  getUseDataRuleButton,
  insert,
  update,
} from "@/api/dataRule";
import { selectOutPut } from "@/model/public/selectModel";
import { treeOutPut } from "@/model/public/treeModel";
import { getAllCorporationSelect } from "@/api/corporation";
import { getAllSystemSelect } from "@/api/system";
import { getCorporationSystemMenuList } from "@/api/menu";
import { getMenuButtonList } from "@/api/button";
import buttonStyleLayout from "@/components/buttonStyle.vue";
import { SysButtonDataOutPut } from "@/model/button/button";
export default defineComponent({
  props: {
    isVisibles: {
      type: Boolean,
    },
    dialogTitle: { type: String },
    modelData: {
      type: Object as PropType<SysDataRuleInput>,
      required: true,
    },
  },

  setup(props, context) {
    //初始加载dom
    onMounted(() => {
      getCorporation();
      //getSystemSelectMsg();
      //getRoleTreeMsg();
    });
    const childRef = ref();
    //是否打开嵌套抽屉
    const innerDrawer = ref<boolean>(false);
    const previewDataRule = ref<string>("");
    //公司数据
    const corporationList = ref<selectOutPut[]>([]);
    //系统数据
    const systemList = ref<selectOutPut[]>([]);
    //菜单数据
    const menuList = ref<treeOutPut[]>([]);
    //公司key
    const corporationKey = ref<string>("");
    //系统key
    const systemKey = ref<string>("");
    //菜单key
    const menuId = ref<string>("");
    //默认展开
    const defaultExpandedKeys = ref<string[]>([]);
    //匹配字段数据
    const matchFieldDataList = ref<matchingSelectExtendOutPut[]>([]);
    //匹配等式数据
    const matchEquationList = ref<selectOutPut[]>([]);

    //tree指定操作
    const defaultProps = {
      children: "children",
      label: "label",
      //设置属于下级角色的菜单，不能勾选
      disabled(data: treeOutPut) {
        if (data.children != null) {
          return true;
        }
      },
    };
    //数据按钮列表
    const sourceDataButtonList = ref<SysButtonDataOutPut[]>([]);
    //匹配公式字符
    const model = ref<SysDataRuleInput>({
      RuleId: "",
      RuleName: "",
      MenuId: "",
      CorporationKey: "",
      SystemKey: "",
      RuleType: RuleTypeEnum.DataClosRule,
      RuleJson: "",
      AnalysisRule: "",
      AnalysisRule_CN: "",
      ButtonIds: [],
      IsOpen: true,
      Remark: "",
      Sort: 1,
      FieldId: ""
    });
    //验证规则
    const ruleFormRef = ref<FormInstance>();
    const rules = reactive<FormRules<typeof model>>({
      RuleName: [
        {
          required: true,
          message: "请填写规则名称!",
          trigger: "blur",
        },
      ],
      AnalysisRule_CN: [
        {
          required: true,
          message: "请创建匹配规则!",
          trigger: "blur",
        },
      ],
      SystemKey: [
        {
          required: true,
          message: "请填选择所属系统!",
          trigger: "blur",
        },
      ],
      MenuId: [
        {
          required: true,
          message: "请填选择所属菜单!",
          trigger: "blur",
        },
      ],
      CorporationKey: [
        {
          required: true,
          message: "请选择所属公司!",
          trigger: "blur",
        },
      ],
    });
    //初始化插件
    const pageList = ref<matchingData[]>([]);
    const initializeData = function () {
      pageList.value = [
        {
          id: "Group-1",
          pid: "0",
          matchGroup: "And",
          level: 1,
          matchingWhere: [
            {
              id: randamId().toString(),
              fieldKey: "",
              matchEquationKey: "",
              matchDataKey: "",
              // matchEquationOptions: [],
              showDataControl: showDataControlEnum.Input,
              showControlDataSourceType: showControlDataSourceEnum.HandInput,
              bindDataSource: [],
              matchDataName: "",
            },
          ],
          children: [],
        },
      ];
    };

    //打开时加载
    const handleDialogOpen = function () {
      matchFieldDataList.value = [];
      matchEquationList.value = [];
      corporationKey.value = props.modelData.CorporationKey;
      systemKey.value = props.modelData.SystemKey;
      menuId.value = props.modelData.MenuId;
      systemClick(props.modelData.SystemKey);
      getSystemSelectMsg(props.modelData.CorporationKey);
      sourceDataButtonList.value = [];
      model.value.ButtonIds = [];
      model.value.CorporationKey = props.modelData.CorporationKey;
      model.value.SystemKey = props.modelData.SystemKey;
      model.value.MenuId = props.modelData.MenuId;
      model.value.Remark = props.modelData.Remark;
      model.value.RuleName = props.modelData.RuleName;
      model.value.RuleId = props.modelData.RuleId;
      model.value.RuleType = props.modelData.RuleType;
      model.value.RuleJson = props.modelData.RuleJson;
      model.value.IsOpen = props.modelData.IsOpen;
      model.value.FieldId = props.modelData.FieldId;
      if (props.modelData.RuleId !== "") {
        model.value.AnalysisRule = props.modelData.AnalysisRule;
        model.value.AnalysisRule_CN = props.modelData.AnalysisRule_CN;
        previewDataRule.value = props.modelData.AnalysisRule_CN;
        pageList.value = parseEntity(props.modelData.RuleJson);
        getUseDataRuleButton({ ruleId: props.modelData.RuleId }).then(
          ({ data, code }) => {
            if (code == 200) {
              model.value.ButtonIds = data;
            }
          }
        );
      } else {
        model.value.AnalysisRule = "";
        model.value.AnalysisRule_CN = "";
        previewDataRule.value = "";
        initializeData();
      }
      if (menuId.value !== "") {
        getDataRuleConfigMsg();
      }
    };

    //获取数据权限配置
    const getDataRuleConfigMsg = function () {
      matchFieldDataList.value = [];
      matchEquationList.value = [];
      GetDataRuleConfig({
        menuId: menuId.value,
        configType: model.value.RuleType,
      }).then(({ data, code }) => {
        if (code == 200) {
          data.map((item: any) => {
            matchFieldDataList.value.push({
              label: item.label,
              value: item.value,
              disabled: item.disabled,
              showDataControl: item.showControl,
              showControlDataSource: item.showControlDataSource,
              matchEquationOptions: item.conditionalEquationList,
            });
            matchEquationList.value = item.conditionalEquationList;
          });
        }
      });
    };

    //公司点击事件
    const corporationClick = function (value: string) {
      if (value == corporationKey.value) {
        model.value.SystemKey = systemKey.value;
        model.value.MenuId = menuId.value;
        systemClick(systemKey.value);
      } else {
        model.value.SystemKey = "";
        model.value.MenuId = "";
      }
      menuList.value = [];
      corporationKey.value = value;
      getSystemSelectMsg(value);
    };

    //系统点击事件
    const systemClick = function (value: string) {
      menuList.value = [];
      model.value.MenuId = "";
      if (value == systemKey.value) model.value.MenuId = menuId.value;
      else model.value.MenuId = "";
      if (value != "")
        getCorporationSystemMenuListMsg(corporationKey.value, value);
    };

    //获取菜单数据
    const getCorporationSystemMenuListMsg = function (
      corporationKey: string,
      systemKey: string
    ) {
      getCorporationSystemMenuList({
        corporationKey: corporationKey,
        systemKey: systemKey,
      }).then(({ data, code }) => {
        if (code == 200) {
          menuList.value = data;
          if (data.length > 0) defaultExpandedKeys.value.push(data[0].key);
        }
      });
    };

    //菜单点击事件
    const menuClick = function (value: string) {
      menuId.value = value;
      getDataRuleConfigMsg();
    };

    //获取下拉框中的公司数据
    const getCorporation = function () {
      getAllCorporationSelect().then(({ data, code }) => {
        if (code == 200) {
          corporationList.value = data;
        }
      });
    };

    //获取下拉框中的系统数据
    const getSystemSelectMsg = function (corporationKey: string) {
      getAllSystemSelect({ corporationKey: corporationKey }).then(
        ({ data, code }) => {
          if (code == 200) {
            systemList.value = data;
          }
        }
      );
    };

    // 模型转换
    const parseEntity = (json: string): matchingData[] => {
      return JSON.parse(json) as matchingData[];
    };
    //预览公式
    const previewClick = function () {
      if (childRef.value != null) {
        childRef.value
          .GetMatchData(model.value.MenuId, model.value.RuleType)
          .then((res: matchResultData) => {
            if (res.isSuccess) {
              previewDataRule.value = res.ruleExpression.analysisRule_CN;
            } else {
              ElMessage.error(res.msg);
            }
          });
      }
    };

    //确认数据规则
    const confirmDataRuleClick = function () {
      if (childRef.value != null) {
        childRef.value
          .GetMatchData(model.value.MenuId, model.value.RuleType)
          .then((res: matchResultData) => {
            if (res.isSuccess) {
              ElMessage({
                message: res.msg,
                type: "success",
              });
              model.value.AnalysisRule = res.ruleExpression.analysisRule;
              model.value.AnalysisRule_CN = res.ruleExpression.analysisRule_CN;
              previewDataRule.value = res.ruleExpression.analysisRule_CN;
              model.value.RuleJson = res.matchRuleJson;
              innerDrawer.value = false;
            } else {
              ElMessage.error(res.msg);
            }
          });
      }
    };

    //保存事件
    const saveClick = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          if (props.modelData.RuleId == "") {
            insert(model.value).then(({ code, msg }) => {
              if (code == 200) {
                handleClose();
                ElMessage({
                  message: msg,
                  type: "success",
                });
              }
            });
          } else {
            update(model.value).then(({ code, msg }) => {
              if (code == 200) {
                handleClose();
                ElMessage({
                  message: msg,
                  type: "success",
                });
              }
            });
          }
        }
      });
    };

    //显示嵌套抽屉
    const setDataRuleClick = function () {
      if (menuId.value === "" || menuId.value === undefined) {
        ElMessage.warning("请先选择所属菜单");
      } else {
        innerDrawer.value = true;
      }
    };

    //关闭嵌套抽屉
    const closeInnerDrawerClick = function () {
      innerDrawer.value = false;
    };

    //是否显示dialog
    const dialogVisibled = computed(() => {
      return props.isVisibles;
    });

    //关闭事件
    const handleClose = () => {
      context.emit("closeBnt");
    };

    return {
      handleClose,
      dialogVisibled,
      handleDialogOpen,
      saveClick,
      pageList,
      previewClick,
      childRef,
      RuleTypeEnum,
      model,
      innerDrawer,
      ruleFormRef,
      rules,
      setDataRuleClick,
      closeInnerDrawerClick,
      previewDataRule,
      confirmDataRuleClick,
      corporationClick,
      systemClick,
      corporationList,
      systemList,
      menuList,
      corporationKey,
      systemKey,
      menuId,
      defaultExpandedKeys,
      defaultProps,
      sourceDataButtonList,
      menuClick,
      matchFieldDataList,
      matchEquationList,
    };
  },
  components: { matchFormula, buttonStyleLayout },
});
</script>
          
          <style scoped>
.divStyle {
  margin: 10px;
}

.treeStyle {
  margin: 10px;
  max-height: 650px;
  overflow-y: auto;
}

/* 对于 Vue scoped 样式 */
.custom-transfer ::v-deep .el-transfer-panel {
  width: 400px;
}

/* 全局样式或非 scoped 样式 */
.custom-transfer .el-transfer-panel {
  width: 400px;
}
</style>